package mc.web;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mc.bus.IBazaAlergenGrupa;
import mc.bus.IBazaAlergenow;
import mc.bus.IBazaLekarzy;
import mc.domain.Alergen;
import mc.domain.Alergen_na_karcie;
import mc.domain.AlergenGrupa;
import mc.domain.KartaTestow;
import mc.domain.Lekarz;
import mc.domain.Pacjent;
import mc.web.propertyeditors.LekarzEditor;
import mc.web.propertyeditors.PacjentEditor;
import mc.web.propertyeditors.TestEditor;

import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.userdetails.UserDetails;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class TestyFormController extends SimpleFormController {

	private final Logger logger = Logger.getLogger(getClass());
	private LekarzEditor lekarzeditor;
	private PacjentEditor pacjenteditor;
	private ResourceBundleMessageSource messagesource;
	private TestEditor testeditor;
	private IBazaLekarzy bazalekarzy;
	private IBazaAlergenow bazaalergenow;
	private IBazaAlergenGrupa bazagrup;

	@Override
	protected Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception {
		logger.info("referenceData");
		Map<String, Object> refdata = new HashMap<String, Object>();
		List<Alergen> allAlergeny = bazaalergenow.getAllAlergeny();
		List<AlergenGrupa> allAlergenGrupa = bazagrup.getAllAlergenGrupa();
		logger.info("Ilosc grup: "+ allAlergenGrupa.size());
		
		List<Alergen_na_karcie> l = new ArrayList<Alergen_na_karcie>();
		Iterator<Alergen> it = allAlergeny.iterator();
		while (it.hasNext()) {
			Alergen alergen = (Alergen) it.next();
			l.add(new Alergen_na_karcie(alergen));
		}
		logger.info("Lista alergenow na karcie: "+l.size());
		refdata.put("alergeny", l);
		refdata.put("grupy", allAlergenGrupa);

		return refdata;
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request) throws Exception {
		logger.info("formBackingObject");
		KartaTestow karta = new KartaTestow();

		UserDetails u = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String login = u.getUsername();
		
		/* biore aktualnie zalogowana tozsamosc z acegi, porownuje z loginami lekarzy, wypelniam 
		 pole lekarza zlecajacego aktualnie zalogowanym */
		List<Lekarz> lekarzeList = bazalekarzy.getAllLekarze();
		Iterator<Lekarz> it = lekarzeList.iterator();

		while (it.hasNext()) {
			Lekarz lekarz = (Lekarz) it.next();
			if (lekarz.getLogin() != null) {
				if (lekarz.getLogin().equals(login)) {
					karta.setLekarz(lekarz);
				}
			}
		}

		return karta;
	}

	@Override
	protected void initBinder(HttpServletRequest arg0, ServletRequestDataBinder binder) throws Exception {

		logger.info("initBinder");
		DecimalFormat decimalFormat = new DecimalFormat();
		// ustawiam separator dziesietny
		DecimalFormatSymbols symbols = new DecimalFormatSymbols();
		symbols.setDecimalSeparator(',');

		SimpleDateFormat dateFormat = new SimpleDateFormat(messagesource.getMessage("data.format", null, null));
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

		decimalFormat.setDecimalFormatSymbols(symbols);
		decimalFormat.setGroupingUsed(false);
		// ustawiam ilosc cyfr w czesci ulamkowej
		decimalFormat.setMaximumFractionDigits(2);
		decimalFormat.setMinimumFractionDigits(2);
		binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, decimalFormat, true));

		binder.registerCustomEditor(Lekarz.class, lekarzeditor);
		binder.registerCustomEditor(Pacjent.class, pacjenteditor);
		binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
		binder.registerCustomEditor(Alergen_na_karcie.class, testeditor);

	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		logger.info("Wchodze w onsubmit");

		String zapisz = request.getParameter("zapisz");

		if (StringUtils.isNotEmpty(zapisz)) {
			Map<String, Object> model = new HashMap<String, Object>();
			// model.put("karta", command);
			// model.put("lekarz", new Lekarz("Roman", "Czeresniak",
			// "2131434"));
			return new ModelAndView("testy.lista", errors.getModel());
		}

		return showForm(request, response, errors);

	}

	public ResourceBundleMessageSource getMessagesource() {
		return messagesource;
	}

	public void setMessagesource(ResourceBundleMessageSource messagesource) {
		this.messagesource = messagesource;
	}

	public LekarzEditor getLekarzeditor() {
		return lekarzeditor;
	}

	public void setLekarzeditor(LekarzEditor lekarzeditor) {
		this.lekarzeditor = lekarzeditor;
	}

	public PacjentEditor getPacjenteditor() {
		return pacjenteditor;
	}

	public void setPacjenteditor(PacjentEditor pacjenteditor) {
		this.pacjenteditor = pacjenteditor;
	}

	public TestEditor getTesteditor() {
		return testeditor;
	}

	public void setTesteditor(TestEditor testeditor) {
		this.testeditor = testeditor;
	}

	public IBazaLekarzy getBazalekarzy() {
		return bazalekarzy;
	}

	public void setBazalekarzy(IBazaLekarzy bazalekarzy) {
		this.bazalekarzy = bazalekarzy;
	}

	public IBazaAlergenow getBazaalergenow() {
		return bazaalergenow;
	}

	public void setBazaalergenow(IBazaAlergenow bazaalergenow) {
		this.bazaalergenow = bazaalergenow;
	}

	public IBazaAlergenGrupa getBazagrup() {
		return bazagrup;
	}

	public void setBazagrup(IBazaAlergenGrupa bazagrup) {
		this.bazagrup = bazagrup;
	}
	
	
	
	

}
